package com.houmeiyuan.huiguniang.service;


import com.houmeiyuan.huiguniang.common.HttpConfig;
import net.sf.json.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Service
public class WXLoginService {

    @Value("${wxAppId}")
    private String appId;
    @Value("${wxAppSecret}")
    private String appSecret;

    private String getSessionUrl = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 微信小程序用户登录，获取openId等信息
     *
     * @param code
     * @param response
     * @return
     */
    public Map<String, Object> onLogin(String code, HttpServletResponse response) {

        Map<String, Object> result = new HashMap<>();
        String url = getSessionUrl + "?appid=" + appId +
                "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        CloseableHttpClient client;
        client = HttpClients.custom()
                .build();
        CloseableHttpResponse resultResponse;
        resultResponse = HttpConfig.doGet(url, response, client);
        String res = HttpConfig.readResponse(resultResponse);
        JSONObject obj = JSONObject.fromObject(res);
        result = obj;
        return result;
    }
}
